﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
using System.IO;
/// <summary>
/// Summary description for SendMail
/// </summary>
public class SendMail
{
    public string Templatefile { get; set; }
    public string Subject { get; set; }
    public string DisplayName { get; set; }
    public string Content { get; set; }
    public string To { get; set; }
    public bool IsHtml { get; set; }
    public bool IsSSL { get; set; }
    public string Title { get; set; }
    public string Sender { get; set; }
    public string Email { get; set; }
    public string ListEmail { get; set; }



	public SendMail()
	{
	    this.Templatefile = "";
	    this.Subject = "";
	    this.DisplayName = "";
	    this.Content = "";
	    this.To = "";
	    this.IsHtml = true;
	    this.IsSSL = true;
	}
    public bool SendEMail()
    {
        try
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(FormAddress, this.DisplayName);
                mail.To.Add(this.To);
                mail.Subject = this.Subject;
                mail.Body = this.getContentMail(this.Templatefile);
                mail.IsBodyHtml = this.IsHtml;
                SmtpClient client = new SmtpClient();
                client.EnableSsl = this.IsSSL;
                client.Send(mail);
            }
        }
        catch (SmtpException ex)
        {
            return false;
        }
        return true;
    }
    private String FormAddress
    {
        get
        {
            SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection
                ("system.net/mailSettings/smtp");
            return cfg.Network.UserName;
        }
    }
    public string getContentMail(string templatefile)
    {
        if(File.Exists(templatefile))
        {
            StreamReader sr = new StreamReader(templatefile);

            sr = File.OpenText(templatefile);
            string contents = sr.ReadToEnd();
            contents = contents.Replace("[Sender]", this.Sender.Trim());
            contents = contents.Replace("[Email]", this.FormAddress);
            contents = contents.Replace("[Content]", this.Content);
            contents = contents.Replace("[DateTime]", DateTime.Now.ToShortDateString());
            return contents;
        }
        else
        {
            return "File không tồn tại";
        }

    }
}